//
//  MainViewController.swift
//  WeiBo
//
//  Created by 姜伦 on 17/1/13.
//  Copyright © 2017年 DjangoGG. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {
    
    override func viewDidLoad() {
        super.viewDidLoad()

        addChildViewControllers()
        setupComposeButton()
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        tabBar.bringSubview(toFront: composeButton)
    }
    
    let composeButton = UIButton(withImage: "tabbar_compose_icon_add", backImage: "tabbar_compose_button")
    
    @objc fileprivate func clickComposeButton() {
        print("点击了发布按钮")
    }

}

extension MainViewController {
    
    /// 设置中间的发布按钮
    fileprivate func setupComposeButton() {
        
        tabBar.addSubview(composeButton)
        
        let count = childViewControllers.count
        let width = tabBar.bounds.width / CGFloat(count)
        composeButton.frame = tabBar.bounds.insetBy(dx: 2 * width + 1, dy: 0)
        
        composeButton.addTarget(self, action: #selector(clickComposeButton), for: .touchUpInside)
    }
    
    /// 添加子控制器
    fileprivate func addChildViewControllers() {
        
        addChildViewController(HomeViewController(), title: "首页", icon: "tabbar_home")
        addChildViewController(MessageViewController(), title: "消息", icon: "tabbar_message_center")
        addChildViewController(UIViewController()) // 为中间的按钮留出位置
        addChildViewController(DiscoverViewController(), title: "发现", icon: "tabbar_discover")
        addChildViewController(MineViewController(), title: "我", icon: "tabbar_profile")
    }
    
    private func addChildViewController(_ vc: UIViewController, title: String, icon: String) {
        
        vc.title = title
        vc.tabBarItem.image = UIImage(named: icon)
        
        let nav = UINavigationController(rootViewController: vc)
        
        addChildViewController(nav)
    }
}
